<template>
  <view class="container">
    <!-- 咨询师信息区块 -->
    <view class="consultant-info">
      <image :src="consultant.psy_pic" class="avatar"></image>
      <view class="info-text">
        <text class="name">{{ consultant.psy_name }}</text>
        <text class="id">ID: {{ consultant.psy_id }}</text>
      </view>
    </view>

    <!-- 页面下部区块 -->
    <view class="bottom-section">
      <!-- 日期选择 -->
      <view class="input-row">
        <text>日期选择</text>
        <picker mode="date" :value="selectedDate" @change="handleDateChange">
          <view class="picker">
            {{ selectedDate || '请选择日期' }}
          </view>
        </picker>
      </view>

      <!-- 开始时间选择器 -->
      <view class="input-row">
        <text>开始时间</text>
        <picker
          mode="time"
          :value="selectedStartTime"
          :start="'08:00'"
          :end="'17:10'"
          :step="'00:50'"
          @change="handleStartTimeChange"
        >
          <view class="picker">
            {{ selectedStartTime || '请选择开始时间' }}
          </view>
        </picker>
      </view>

      <!-- 结束时间显示（自动计算） -->
      <view class="input-row">
        <text>结束时间</text>
        <view class="picker">
          {{ selectedEndTime || "根据开始时间自动计算" }}
        </view>
      </view>
    </view>

    <!-- 额外信息 -->
    <view class="extra-info">
      <text>咨询时长：50分钟</text>
      <text>咨询师联系方式: {{ consultant.psy_phone }}</text>
    </view>

    <!-- 底部提示和按钮 -->
    <view class="footer">
      <view class="tip-box">温馨提示：请仔细核对预约信息后提交</view>
      <button type="primary" @click="submitAppointment">提交预约</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      consultant: {
        psy_pic: '',
        psy_name: '',
        psy_id: '',
        psy_phone: ''
      },
      selectedDate: '',
      selectedStartTime: ''
    };
  },
  computed: {
    selectedEndTime() {
      if (!this.selectedStartTime) {
        return '';
      }
      const [hours, minutes] = this.selectedStartTime.split(':').map(Number);
      let endHours = hours;
      let endMinutes = minutes + 50;

      if (endMinutes >= 60) {
        endMinutes -= 60;
        endHours += 1;
      }

      if (endHours >= 24) {
        endHours = 0;
      }

      return `${endHours.toString().padStart(2, '0')}:${endMinutes.toString().padStart(2, '0')}`;
    }
  },
  methods: {
    // 处理日期选择变化
    handleDateChange(e) {
      this.selectedDate = e.detail.value;
    },
    // 处理开始时间选择变化
    handleStartTimeChange(e) {
      this.selectedStartTime = e.detail.value;
    },
    // 从服务器获取咨询师信息
    async fetchConsultantData(id) {
      try {
        const res = await uni.request({
          url: `http://127.0.0.1:5001/api_1_0/psyConsultant/${id}`,
          method: 'GET'
        });

        if (res.statusCode === 200 && res.data.code === '2000') {
          this.consultant = res.data.data[0];
        } else {
          uni.showToast({ title: '获取咨询师信息失败', icon: 'none' });
        }
      } catch (err) {
        console.error('获取咨询师信息失败', err);
        uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
      }
    },
    // 提交预约
    async submitAppointment() {
      if (!this.selectedDate || !this.selectedStartTime) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      const appointmentData = {
        psy_id: this.consultant.psy_id,
        date: this.selectedDate, // 日期格式为 YYYY-MM-DD
        start_time: `${this.selectedDate} ${this.selectedStartTime}:00`, // 日期 + 时间，格式为 YYYY-MM-DD HH:MM:SS
        end_time: `${this.selectedDate} ${this.selectedEndTime}:00`, // 日期 + 时间，格式为 YYYY-MM-DD HH:MM:SS
        is_online: 1, // 1 表示线上预约
        status: 1 // 默认状态为 1（待确认）
      };

      try {
        const res = await uni.request({
          url: 'http://127.0.0.1:5001/api_1_0/consulting',
          method: 'POST',
          data: appointmentData,
          header: {
            'Content-Type': 'application/json'
          }
        });

        if (res.statusCode === 200 && res.data.code === '2000') {
          uni.showToast({ title: '预约成功', icon: 'success' });
          uni.navigateTo({ url: '/pages/user/consult/ok' });
        } else {
          uni.showToast({ title: `预约失败: ${res.data.message || '未知错误'}`, icon: 'none' });
        }
      } catch (err) {
        console.error('提交预约失败', err);
        uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
      }
    }
  },
  onLoad(options) {
    const consultantId = options.id;
    if (consultantId) {
      this.fetchConsultantData(consultantId);
    } else {
      uni.showToast({ title: '未找到咨询师ID，请返回重试', icon: 'none' });
      uni.navigateBack();
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
}

.consultant-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 15px;
}

.info-text {
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 18px;
  font-weight: bold;
}

.id {
  font-size: 14px;
  color: #888;
}

.bottom-section {
  margin-top: 20px;
}

.input-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.picker {
  flex: 2;
  text-align: right;
  background-color: #fff;
  padding: 5px;
  border-radius: 4px;
}

.footer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tip-box {
  margin-bottom: 15px;
  font-size: 14px;
  color: #81B337;
}

button {
  width: 90%;
  padding: 10px 20px;
  background-color: #81B337;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 16px;
}

.extra-info {
  margin-top: 20px;
}

.extra-info text {
  display: block;
  margin-bottom: 10px;
  font-size: 16px;
}
</style>